package com.adk.backend.controller;

import com.adk.backend.common.Result;
import com.adk.backend.service.PermissionService;
import com.adk.backend.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 权限控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/permission")
public class PermissionController {
    
    @Autowired
    private PermissionService permissionService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 获取当前用户的权限信息
     */
    @GetMapping("/info")
    public Result<Map<String, Object>> getPermissionInfo(
            @RequestHeader(value = "Authorization", required = false) String token) {
        try {
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            if (token == null) {
                return Result.error("未登录");
            }
            
            // 从Token获取用户类型
            Integer userType = null;
            try {
                io.jsonwebtoken.Claims claims = jwtUtil.getClaimsFromToken(token);
                if (claims != null) {
                    Object userTypeObj = claims.get("userType");
                    if (userTypeObj != null) {
                        userType = Integer.valueOf(userTypeObj.toString());
                    }
                }
            } catch (Exception e) {
                log.error("获取用户类型失败", e);
            }
            
            if (userType == null) {
                return Result.error("Token无效");
            }
            
            Map<String, Object> permissions = permissionService.getUserPermissions(userType);
            return Result.success(permissions);
        } catch (Exception e) {
            log.error("获取权限信息失败", e);
            return Result.error("获取权限信息失败");
        }
    }
}

